var logger = require('../../common').logger;
var query = require('../../common').Query;
var map = require('../../common').Mapping;

exports.loginPage = function (req, res) {
    if (req.session.uid) {
        if(!!req.query.target) {
            res.redirect(req.query.target);
            return;
        }
        switch (map.userRole[req.session.uid]) {
            case 'manager' :
                res.redirect('/project/find');
                break;
            case 'admin' :
                res.redirect('/member/find');
                break;
            case 'member' :
                res.redirect('/plan/list');
                break;
            case 'intern' :
                res.redirect('/plan/list');
                break;
        }
    } else {
        res.render("loginTpl", null);
    }
};

exports.login = function (req, res) {
    query(map.sql.login, res, {username: req.body.username}, function (rows) {
        if (rows.length != 1) {
            res.send({error: 405, description: map.error[405]});
        } else {
            if (req.body.pwd == rows[0].pwd) {
                req.session.uid = rows[0].u_id;
                if (req.body.remember) {
                    var expires = 20 * 86400 * 1000;
                    var buffer = new Buffer(rows[0].u_id + ":" + req.headers.host);
                    res.cookie('remember', buffer.toString('base64'), {maxAge: expires, path: '/', httpOnly: true});
                }
                logger.info("User Login: " + map.userName[rows[0].u_id]);
                res.send('success');
            } else {
                res.send({error: 406, description: map.error[406]});
            }
        }
    });
};

exports.logout = function (req, res) {
    logger.info('User logout : ' + map.userName[req.session.uid]);
    req.session.uid = '';
    res.cookie('remember', '', {maxAge: -1});
    res.redirect('/');
};

exports.modifyPwdPage = function (req, res) {
    res.render('modifyPwdTpl', null);
};

exports.getMapping = function (req, res) {
    query("SELECT u_id AS id, u_name AS `name`,role FROM `user` WHERE `status` = 'active'",res,{}, function (rows) {
        map.userName = {};
        map.userRole = {};
        for (var i in rows) {
            map.userName[rows[i].id] = rows[i].name;
            map.userRole[rows[i].id] = rows[i].role;
        }
        logger.info("User Information ReCached");
        res.send({
            name: map.userName,
            role: map.userRole,
            p_status: map.projectStatus,
            statusKey: map.statusKey,
            roleKey: map.roleKey
        });
    });
};

exports.validateUnique = function (req, res) {
    query("SELECT count(*) FROM " + req.body.schema + " WHERE " + req.body.attr + "=" + req.body.value, res, {}, function (rows) {
        if (rows[0]['count(*)'] == 0) {
            res.send("success");
        } else {
            res.send("fail");
        }
    });
};

exports.leaveTeam = function(req,res) {
    query("UPDATE user SET team = NULL,manager=NULL WHERE u_id = #id", res, req.body, function (rows) {
        if (rows.affectedRows == 1) {
            res.send('success');
        } else {
            res.send({error: 503, description: map.error[503]});
        }
    });
};

exports.updateSetting = function (req, res) {
    query(map.sql.updateSetting, res, req.body, function (rows) {
        if (rows.affectedRows == 1) {
            res.send('success');
        } else {
            res.send({error: 503, description: map.error[503]});
        }
    });
};

exports.modifyPassword = function (req, res) {
    query(map.sql.modifyPwd, res, {
        oldPwd: req.body.oldPwd,
        newPwd: req.body.newPwd,
        id: req.session.uid
    }, function (rows) {
        if (rows.affectedRows == 1) {
            req.session.uid = '';
            res.cookie('remember', '', {maxAge: -1});
            res.send("success");
        } else {
            res.send({error: 406, description: map.error[406]});
        }
    });
};